package com.example.cyw.mycontextprover;

import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class ListActivity extends AppCompatActivity implements DelListen{
     private ListView listView;
     private Button btn_back;
    private ArrayList<student>  mlist;
    StuAdapter Adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        initView();
        initList();
       Adapter=new StuAdapter(ListActivity.this,mlist,ListActivity.this);
        listView.setAdapter(Adapter);
    }

    private void initList() {
        Uri uri=Uri.parse("content://com.gdcp.studb/student");
        Cursor cur=getContentResolver().query(uri,null,null,null,null);
        for (cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
            int id=cur.getInt(0);
            String name=cur.getString(1);
           int age=cur.getInt(2);
         student s=new student(id,name,age);
            mlist.add(s);
        }
        cur.close();
    }

    private void initView() {
        listView= (ListView) findViewById(R.id.listView);
        btn_back= (Button) findViewById(R.id.btn_back);
        mlist=new ArrayList<student>();
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void del(int id) {
        Uri uri=Uri.parse(MyContentProvider.URI_STUDENT);
        String where = "id = " + id;
        getContentResolver().delete(uri,where,null);
        Cursor cur=getContentResolver().query(uri,null,null,null,null);
        mlist.clear();
        for (cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
            int bid=cur.getInt(0);
            String name=cur.getString(1);
            int age=cur.getInt(2);
            student s=new student(bid,name,age);
            mlist.add(s);
        }
        cur.close();
        Adapter.notifyDataSetChanged();

    }
}
